package com.bwie.esdemo0122.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.esdemo0122.controller.CameraController;
import com.bwie.esdemo0122.service.EsDocService;
import com.bwie.esdemo0122.service.EsIndexService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class EsDocServiceImpl implements EsDocService {

    @Autowired
    private EsIndexServiceImpl esIndexService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean save(Map<String, Object> esData) {

        //参数校验
        if (checkParms(esData)){
            //构建保存到es的请求体
            BulkRequest bulkRequest = new BulkRequest();
            //取出datas集合，并遍历
            List<Map<String,Object>> datas = (List<Map<String, Object>>) esData.get("datas");
            for (Map<String, Object> data : datas) {
                IndexRequest indexRequest = new IndexRequest(esData.get("indexName").toString());
                //校验id是否自动生成
                if (data.get("id") != null){
                    indexRequest.id(data.get("id").toString());
                }
                indexRequest.source(JSONObject.toJSONString(data.get("data")), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            //调用客户端完成插入
            try {
                BulkResponse bulkRep = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                //依次判断下bulkRep是否成功,打印出失败的数据
                for (int i = 0; i < bulkRep.getItems().length; i++) {
                    if (bulkRep.getItems()[i].getResponse() != null){
                        System.out.println("第" + (i + 1) + "条数据插入成功");
                    }else {
                        System.out.println("第" + (i + 1) + "条数据插入失败");
                        System.out.println(bulkRep.getItems()[i].getResponse().toString());
                    }
                }
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    private boolean checkParms(Map<String, Object> esData) {
        //校验索引名称是否为空
        if (esData.get("indexName") == null){
            System.out.println("索引名称不能为空");
            return false;
        }else {
            if (!esIndexService.existsIndex(esData.get("indexName").toString())){
                System.out.println("索引不存在");
                return false;
            }
        }
        //校验data是否为空
        if (esData.get("datas") == null){
            System.out.println("要插入的数据不能为空");
            return false;
        }
        return true;
    }

    @Override
    public boolean update(Map<String, Object> esData) {
        return false;
    }

    @Override
    public boolean delete(String indexName, String docId) {
        return false;
    }

    @Override
    public Map<String, Object> query(String indexName, String docId) {
        //查询数据库，得到一个List
        List<Object> data  = new ArrayList<>();//假设从数据库查出来
        CameraController.cache.put("key",data);

        //取数据
        CameraController.cache.get("key");
        //构建查询请求体
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder searchSourceBuilder = getSourceBuild();
        System.out.println(searchSourceBuilder.toString());

        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(searchResponse.toString());
            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
            //TODO 解析返回结果
        } catch (IOException e) {
            e.printStackTrace();
            //将报错信息保存到异常日志表（调用时间、调用类、调用方法、调用参数、异常信息）
        }
        return null;
    }

    private SearchSourceBuilder getSourceBuild() {

        //构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建bool查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //构建精确查询
        QueryBuilder termQueryBuilder= QueryBuilders.termQuery("tag","tag1");
        //构建范围查询
        RangeQueryBuilder rangePriceQuery = QueryBuilders.rangeQuery("price");
        rangePriceQuery.gte(100);
        rangePriceQuery.lte(200);
        //构建mustQuery
        boolQueryBuilder.must(termQueryBuilder);
        boolQueryBuilder.must(rangePriceQuery);
        searchSourceBuilder.query(boolQueryBuilder);
        return searchSourceBuilder;
    }
}
